#include "sdcontroller.h"
#include "mc_uiprotocol.h"
#include "database.h"

SDController::SDController(QObject *parent) : QObject(parent)
{
    mp_SDBuildingMapModel = NULL;
}
void SDController::getFloorDevice(int buildtype, QVariant buildindex)
{
    if(mp_SDBuildingMapModel == NULL){
        qDebug()<<FLINE<<"Error SD Building Model is NULL";
    }
    qDebug()<<FLINE<<"SD Usr Clicked "<<buildtype<<buildindex;
    mp_SDBuildingMapModel->userClickedDistrickItem(buildtype , buildindex);

    QSqlQuery query;
    int buildingnum = mp_SDBuildingMapModel->m_CurrentBuild.mid(1).toInt();
    int flooenum = mp_SDBuildingMapModel->m_CurrentFloor.mid(1).toInt();

    QString strQuery = QString("select ltid,xpos,ypos,online from lt where buildingnum=%1 and floornum=%2 ").arg(buildingnum).arg(flooenum);
    if(!query_database(strQuery ,query))
        return;
    QString ltid;int ltxpos=0;int ltypos=0; int ltonline=0;QString lticonclolor;
    while (query.next()) {
        ltid = query.value("ltid").toString();
        ltxpos = query.value("xpos").toInt();
        ltypos = query.value("ypos").toInt();
        ltonline = query.value("online").toInt();
        if(ltonline > 0)
            lticonclolor = "green";
        else
            lticonclolor = "grey";

        emit sdInit("LT","",ltid,0,lticonclolor,ltxpos,ltypos,0,0,"");

    }


    strQuery =  QString("select id,ltid,port,xpos,ypos,online,emglv,emgno,emgtime,power from sensor where buildingnum=%1 and floornum=%2")
            .arg(buildingnum).arg(flooenum);
    if(!query_database(strQuery,query))
        return;
    QString sdisn;QString ltisn;int port=0;int xpos=0;int ypos=0;int online=0;int emglv=0;int emgno=0;QString emgtime;int power=0;
    while (query.next()) {
        sdisn = query.value("id").toString();
        ltisn = query.value("ltid").toString();
        port = query.value("port").toUInt();
        xpos = query.value("xpos").toUInt();
        ypos = query.value("ypos").toUInt();
        online = query.value("online").toUInt();
        emglv = query.value("emglv").toUInt();
        emgno = query.value("emgno").toUInt();
        emgtime = query.value("emgtime").toString();
        power = query.value("power").toUInt();
        QString iconstatecolor;
        if(online > 0)
            iconstatecolor = "green";
        else
            iconstatecolor = "grey";

        if(emglv >= SD100_EMG_TRIG_TIMES)
            iconstatecolor = "red";

       emit sdInit("SD" ,sdisn,ltisn ,port,iconstatecolor,xpos,ypos,power,emgno,emgtime);

    }


}

void SDController::setSDQmlViewRootItem(const QObject *rootqmlview)
{
  mp_SDBuildingMapModel = new BuildingMapModel(rootqmlview->findChild<QObject*>("objsdbuildview"));
  getFloorDevice(1 , mp_SDBuildingMapModel->m_CurrentDistrcik);

  init2DMapDevicesNumInfo();
}
void SDController::processData(QByteArray data)
{
    GUI_SHM_PACKET_HEADER *pGUIPacketHead = (GUI_SHM_PACKET_HEADER*)(data.data());
    GUI_SHM_LT_INFO *pLTInfo = (GUI_SHM_LT_INFO*)(data.data()+sizeof(GUI_SHM_PACKET_HEADER));
    GUI_SHM_SUB_DEV_INFO *pSDInfo = (GUI_SHM_SUB_DEV_INFO*)(data.data()+sizeof(GUI_SHM_PACKET_HEADER));

    if (pGUIPacketHead->devtype == DEVICE_SD100) {
        QString sdisn  = QString(pSDInfo->subdevisn);
        int sdno = pSDInfo->subdevno;
        QString sdevent = "";
        switch (pSDInfo->cmd) {
        case CMD_GUI_DEVICE_ON:
            sdevent = "Online";
            break;
        case CMD_GUI_DEVICE_OFF:
            sdevent = "Offline";
            break;
        case CMD_START_ALARM:
            sdevent = "Emg";
            break;
        case CMD_CANCEL_ALARM:
            sdevent = "CancelEmg";
            break;
        case CMD_LOW_POWER_ALARM:
            sdevent = "Lowpower";
            break;
        case CMD_CANCEL_LOW_POWER_ALARM:
            sdevent = "CancelLowpower";
            break;
        }
        qDebug()<<FLINE<<"SD:"<<sdisn<<"Emit Event";
        sdEvent(sdisn , sdevent , false);

    }
    else if(pGUIPacketHead->devtype == DEVICE_LT){
        QString ltisn = QString(pLTInfo->ltisn);
        QString ltevent = "";
        switch (pLTInfo->cmd) {
        case CMD_GUI_DEVICE_ON:
            ltevent = "Online";
            break;
        case CMD_GUI_DEVICE_OFF:
            ltevent = "Offline";
            break;
        }
        sdEvent(ltisn , ltevent , true);

    }
    else {
        return;
    }

}
void SDController::update_position(const QString &id, const QString &type, int x, int y)
{
    QString strQuery;
    if (type == "SD") {
        strQuery = QString("UPDATE sensor SET Xpos = %1, Ypos = %2 WHERE id = '%3';").arg(x).arg(y).arg(id);
    }
    else if (type == "LT") {
        strQuery = QString("UPDATE lt SET Xpos = %1, Ypos = %2 WHERE ltid = '%3';").arg(x).arg(y).arg(id);
    }

    exec_database(strQuery);
}
void SDController::setSDEvent(const QString &id , const QString &type, QString event)
{
    QString strQuery;
    if (type == "SD") {
        if(event == "CancelEmg")
            strQuery = QString("UPDATE sensor SET emglv = 0 WHERE id = '%1';").arg(id);
        else if(event == "Online")
            strQuery = QString("UPDATE sensor SET online = 1 WHERE id = '%1';").arg(id);
        else
            return;

    }
    else
       return;
    exec_database(strQuery);

    sdEvent(id , event , false);
}
QString SDController::getSDSateInfo()
{
    QString strQuery = QString("select count(emglv) from sensor where emglv>0");
    QSqlQuery query;
    QString  emgcnt , offlinecnt , onlinecnt ;
    if(query_database(strQuery , query)){
        query.first();
        qDebug()<<FLINE<<"Emg :"<<query.value("count(emglv)");
        emgcnt = query.value(0).toString();
    }

    strQuery = QString("select count(online) from sensor where online=0");
    query.clear();
    if(query_database(strQuery , query)){
        query.first();
        qDebug()<<FLINE<<"Offline :"<<query.value(0);
        offlinecnt = query.value(0).toString();
    }


    strQuery = QString("select count(online) from sensor where online=1");
    query.clear();
    if(query_database(strQuery , query)){
        query.first();
        qDebug()<<FLINE<<"Online :"<<query.value(0);
        onlinecnt = query.value(0).toString();
    }

    return emgcnt+"*"+offlinecnt+"*"+onlinecnt;
}
void SDController::init2DMapDevicesNumInfo()
{
   const MapModelList *disModel = mp_SDBuildingMapModel->getDistrickModel();
   const MapModelList *buildModel = NULL;
   const MapModelList *floorModel = NULL;

   QMap<QString , int>DisDevCntList;
   QMap<QString , int>BuildDevCntList;
   QMap<QString , int>BuildFlooeDevCntList;

   for(int DisIndex = 0 ; DisIndex < disModel->rowCount() ; DisIndex++){
       QModelIndex NumIndex = disModel->createIndex(DisIndex , 0 , NULL);
       QString DisStrNum = disModel->data(NumIndex , MapModelList::RoleName_Number).toString();
//       qDebug()<<FLINE<<"SD Init DevCnt "<<DisStrNum;
       DisDevCntList.insert(DisStrNum , 0);

       buildModel = mp_SDBuildingMapModel->getBuildingModel(DisStrNum);
       for(int BuildIndex = 0 ; BuildIndex < buildModel->rowCount() ; BuildIndex++){
           QModelIndex NumIndex = buildModel->createIndex(BuildIndex , 0 , NULL);
           QString BuildStrNum = buildModel->data(NumIndex , MapModelList::RoleName_Number).toString();
//           qDebug()<<FLINE<<"SD Init DevCnt "<<BuildStrNum;
           QString strQuery = QString("select(select count(*) from lt where buildingnum=%1)+(select count(*) from sensor where buildingnum=%1) ")
                   .arg(BuildStrNum.mid(1));
           QSqlQuery query;
           if(query_database(strQuery , query)){
               query.first();
//               qDebug()<<FLINE<<BuildStrNum<<" Dev Cnt"<<query.value(0);
               BuildDevCntList.insert(BuildStrNum , query.value(0).toUInt());
           }

           floorModel = mp_SDBuildingMapModel->getFloorModel(DisStrNum , BuildStrNum);
           for(int FlooeIndex = 0 ; FlooeIndex < floorModel->rowCount() ; FlooeIndex++){
               QModelIndex NumIndex = floorModel->createIndex(FlooeIndex , 0 , NULL);
               QString FlooeStrNum = floorModel->data(NumIndex , MapModelList::RoleName_Number).toString();
//               qDebug()<<FLINE<<"SD Init DevCnt "<<FlooeStrNum;

               QString strQuery = QString("select(select count(*) from lt where buildingnum=%1 and floornum=%2)+(select count(*) from sensor where buildingnum=%1 and floornum=%2) ")
                       .arg(BuildStrNum.mid(1)).arg(FlooeStrNum.mid(1));
               QSqlQuery query;
               if(query_database(strQuery , query)){
                   query.first();
//                   qDebug()<<FLINE<<BuildStrNum<<" Dev Cnt"<<query.value(0);
                   BuildFlooeDevCntList.insert(BuildStrNum+"+"+FlooeStrNum , query.value(0).toUInt());
               }
           }
       }
   }

   mp_SDBuildingMapModel->setNumInfoDevices(DisDevCntList , BuildDevCntList , BuildFlooeDevCntList);

   QString strQuery = QString("select id from sensor");
   QSqlQuery query;
   if(query_database(strQuery , query)){
       while (query.next()) {
           updateSDEmgCntInfo(query.value(0).toString() , "");
       }
   }
}

void SDController::updateSDEmgCntInfo(const QString &sdid , const QString &event)
{
    QString strQuery = QString("select buildingnum , floornum from sensor where id='%1' ").arg(sdid);
    QSqlQuery query; int buildnum, floornum ;
    if(query_database(strQuery , query)){
        query.first();
        buildnum = query.value("buildingnum").toUInt();
        floornum = query.value("floornum").toUInt();
    }


    strQuery = QString("select count(*) from sensor where emglv>0 and buildingnum=%1 and floornum=%2")
            .arg(buildnum).arg(floornum);

    query.clear();
    if(query_database(strQuery , query)){
        query.first();
        qDebug()<<FLINE<<"SD Update Emg Cnt :"<<query.value(0).toUInt();
        mp_SDBuildingMapModel->setEmgDeviceNum("" , "B"+QString::number(buildnum) , "F"+QString::number(floornum) , query.value(0).toUInt());
    }
}
